// Operator Overloading (运算符重载) 示例
program OperatorOverloadingExample;

{$mode objfpc}{$H+}

// 定义一个复数类型，支持运算符重载
type
  TComplex = record
    Real, Imaginary: Double;
    
    // 构造函数
    constructor Create(AReal, AImaginary: Double);
  end;

// 复数类型的构造函数
constructor TComplex.Create(AReal, AImaginary: Double);
begin
  Real := AReal;
  Imaginary := AImaginary;
end;

// 运算符重载函数必须在类型外部定义
// 复数加法运算符重载
operator +(const A, B: TComplex): TComplex;
begin
  Result.Real := A.Real + B.Real;
  Result.Imaginary := A.Imaginary + B.Imaginary;
end;

// 复数减法运算符重载
operator -(const A, B: TComplex): TComplex;
begin
  Result.Real := A.Real - B.Real;
  Result.Imaginary := A.Imaginary - B.Imaginary;
end;

// 复数乘法运算符重载
operator *(const A, B: TComplex): TComplex;
begin
  Result.Real := A.Real * B.Real - A.Imaginary * B.Imaginary;
  Result.Imaginary := A.Real * B.Imaginary + A.Imaginary * B.Real;
end;

// 复数除法运算符重载
operator /(const A, B: TComplex): TComplex;
var
  Denominator: Double;
begin
  Denominator := B.Real * B.Real + B.Imaginary * B.Imaginary;
  if Denominator = 0 then
    raise Exception.Create('复数除法：除数不能为零');
    
  Result.Real := (A.Real * B.Real + A.Imaginary * B.Imaginary) / Denominator;
  Result.Imaginary := (A.Imaginary * B.Real - A.Real * B.Imaginary) / Denominator;
end;

// 复数相等比较运算符重载
operator =(const A, B: TComplex): Boolean;
begin
  Result := (A.Real = B.Real) and (A.Imaginary = B.Imaginary);
end;

// 复数不等比较运算符重载
operator <>(const A, B: TComplex): Boolean;
begin
  Result := not (A = B);
end;

// 正号运算符重载
operator +(const A: TComplex): TComplex;
begin
  Result := A;
end;

// 负号运算符重载
operator -(const A: TComplex): TComplex;
begin
  Result.Real := -A.Real;
  Result.Imaginary := -A.Imaginary;
end;

// 打印复数的辅助过程
procedure PrintComplex(const A: TComplex; const Name: string);
begin
  if A.Imaginary >= 0 then
    WriteLn(Name, ' = ', A.Real:0:2, ' + ', A.Imaginary:0:2, 'i')
  else
    WriteLn(Name, ' = ', A.Real:0:2, ' - ', Abs(A.Imaginary):0:2, 'i');
end;

var
  A, B, C: TComplex;

begin
  WriteLn('=== Pascal 运算符重载示例 ===');
  WriteLn;
  
  // 创建复数
  A := TComplex.Create(3, 4);   // 3 + 4i
  B := TComplex.Create(1, -2);  // 1 - 2i
  
  WriteLn('初始复数:');
  PrintComplex(A, 'A');
  PrintComplex(B, 'B');
  WriteLn;
  
  // 使用重载的运算符进行计算
  WriteLn('运算结果:');
  C := A + B;
  PrintComplex(C, 'A + B');
  
  C := A - B;
  PrintComplex(C, 'A - B');
  
  C := A * B;
  PrintComplex(C, 'A * B');
  
  C := A / B;
  PrintComplex(C, 'A / B');
  WriteLn;
  
  // 比较运算符
  WriteLn('比较运算:');
  if A = B then
    WriteLn('A 等于 B')
  else
    WriteLn('A 不等于 B');
    
  if A <> B then
    WriteLn('A 不等于 B')
  else
    WriteLn('A 等于 B');
  WriteLn;
  
  // 一元运算符
  WriteLn('一元运算:');
  C := +A;
  PrintComplex(C, '+A');
  
  C := -A;
  PrintComplex(C, '-A');
  
  WriteLn;
  WriteLn('运算符重载示例完成。');
  ReadLn;
end.